//
//  RegisterView.m
//  SHHCPhone
//
//  Created by sheng long on 14-6-18.
//  Copyright (c) 2014年 sheng long. All rights reserved.
//

#import "RegisterView.h"

#define APP_SEND_CODE_NUMBER            5
#define APP_SEND_CODE_LOCK_PHONE        @"APP_SEND_CODE_LOCK_PHONE"
#define APP_SEND_CODE_LOCK_TIME         @"APP_SEND_CODE_LOCK_TIME"

@interface RegisterView()<UITextFieldDelegate>
{
    UIScrollView *mainScroll;
    
    //验证码所需
    UIButton *codeButton;
    NSTimer *timer;
    NSInteger codeTimer;
}
@end

@implementation RegisterView

@synthesize viewType,fieldView1,fieldView2,fieldView3,fieldView4;

-(void)setViewType:(RegisterType )type
{
    viewType = type;
    
    mainScroll = [[UIScrollView alloc] initWithFrame:self.bounds];
    [self addSubview:mainScroll];
    [mainScroll setContentSize:self.bounds.size];
    [mainScroll setShowsVerticalScrollIndicator:NO];
    [mainScroll setBounces:NO];
    
    UIButton *bgButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [bgButton addTarget:self action:@selector(closeKeyboard) forControlEvents:UIControlEventTouchUpInside];
    [bgButton setFrame:self.bounds];
    [mainScroll addSubview:bgButton];
    
    fieldView1 = [[TextFieldView alloc] init];
    [mainScroll addSubview:fieldView1];
    
    fieldView2 = [[TextFieldView alloc] init];
    [mainScroll addSubview:fieldView2];

    fieldView3 = [[TextFieldView alloc] init];
    [mainScroll addSubview:fieldView3];
    
    [fieldView1 setBgImage:@"输入框.png" titleImage:@"登录页-手机icon.png" tip:@"输入手机号"];
    fieldView1.textField.keyboardType = UIKeyboardTypeNumberPad;
    
    [fieldView2 setBgImage:@"输入框.png" titleImage:@"注册-输入验证码icon.png" tip:@"输入验证码"];
    fieldView2.textField.keyboardType = UIKeyboardTypeASCIICapable;
    fieldView2.textField.returnKeyType = UIReturnKeyNext;
    [fieldView2.textField addTarget:self action:@selector(nextButt:) forControlEvents:UIControlEventEditingDidEndOnExit];
    
    [fieldView3 setBgImage:@"输入框.png" titleImage:@"登录页-密码icon.png" tip:@"输入密码"];
    fieldView3.textField.keyboardType = UIKeyboardTypeASCIICapable;
    fieldView3.textField.returnKeyType = UIReturnKeyDone;
    [fieldView3.textField setSecureTextEntry:YES];
    [fieldView3.textField addTarget:self action:@selector(nextButt:) forControlEvents:UIControlEventEditingDidEndOnExit];
    
    [fieldView1 setCenter:CGPointMake(self.frame.size.width/2, 25+fieldView1.frame.size.height/2)];
    [fieldView2 setCenter:CGPointMake(self.frame.size.width/2, 19+fieldView1.frame.size.height+fieldView1.frame.origin.y+fieldView2.frame.size.height/2)];
    [fieldView3 setCenter:CGPointMake(self.frame.size.width/2, 19+fieldView2.frame.size.height+fieldView2.frame.origin.y+fieldView3.frame.size.height/2)];
    
    [fieldView1.textField setDelegate:self];
    [fieldView2.textField setDelegate:self];
    [fieldView3.textField setDelegate:self];
    
    UIButton *button1 = [OftenMenthod setButtonTitle:@"确定"];
    [mainScroll addSubview:button1];
    [button1 addTarget:self action:@selector(doneButt) forControlEvents:UIControlEventTouchUpInside];
    [button1 setCenter:CGPointMake(fieldView3.center.x, fieldView3.frame.size.height+fieldView3.frame.origin.y+46+button1.frame.size.height/2)];
    
//    if (self.viewType == Update_Type) {
    
        fieldView3.textField.returnKeyType = UIReturnKeyNext;
        
        fieldView4 = [[TextFieldView alloc] init];
        [mainScroll addSubview:fieldView4];
        [fieldView4 setBgImage:@"输入框.png" titleImage:@"登录页-密码icon.png" tip:@"再次输入密码"];
        fieldView4.textField.keyboardType = UIKeyboardTypeASCIICapable;
        fieldView4.textField.returnKeyType = UIReturnKeyDone;
        [fieldView4.textField setSecureTextEntry:YES];
        [fieldView4.textField addTarget:self action:@selector(nextButt:) forControlEvents:UIControlEventEditingDidEndOnExit];
        [fieldView4 setCenter:CGPointMake(self.frame.size.width/2, 19+fieldView3.frame.size.height+fieldView3.frame.origin.y+fieldView4.frame.size.height/2)];
        [fieldView4.textField setDelegate:self];

        [button1 setCenter:CGPointMake(fieldView4.center.x, fieldView4.frame.size.height+fieldView4.frame.origin.y+46+button1.frame.size.height/2)];
//    }
    
    if (YES) {
        //获取验证码
        codeButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [codeButton setFrame:CGRectMake(0, 0, 72, 30)];
        [codeButton setBackgroundColor:GET_COLOR(@"ff8cb7")];
        [codeButton setTitle:@"获取验证码" forState:UIControlStateNormal];
        [codeButton setShowsTouchWhenHighlighted:YES];
        [codeButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [codeButton.titleLabel setFont:[UIFont boldSystemFontOfSize:12]];
        [mainScroll addSubview:codeButton];
        [codeButton addTarget:self action:@selector(getButt:) forControlEvents:UIControlEventTouchUpInside];
        [codeButton setCenter:CGPointMake(fieldView2.frame.origin.x+fieldView2.frame.size.width-4-codeButton.frame.size.width/2, fieldView2.center.y)];
        
        CGRect rect = fieldView2.textField.frame;
        rect.size.width = codeButton.frame.origin.x-rect.origin.x-22;
        fieldView2.textField.frame = rect;
    }
}

//锁住验证码
-(void)lockCode
{
    //记录当前设备发送次数
    NSString *msg = [APP_USERDEFAULTS valueForKey:APP_SEND_CODE_LOCK_PHONE];
    NSMutableArray *array = [NSMutableArray arrayWithCapacity:1];
    if (msg) {
        array = [NSMutableArray arrayWithArray:[msg objectFromJSONString]];
    }
    NSDictionary *dic = @{APP_SEND_CODE_LOCK_TIME: [NSNumber numberWithFloat:[[NSDate date] timeIntervalSince1970]]};
    [array addObject:dic];
    [APP_USERDEFAULTS setValue:[array JSONString] forKey:APP_SEND_CODE_LOCK_PHONE];
    
    //发送验证码按钮置灰
    [codeButton setBackgroundColor:[UIColor grayColor]];
    [codeButton setAlpha:.7];
    [codeButton setTitleColor:[UIColor lightTextColor] forState:UIControlStateNormal];
    [codeButton setShowsTouchWhenHighlighted:NO];
    
    //60s不准输入验证码
    codeTimer = 60;
    [codeButton setTitle:@"发送中(60)" forState:UIControlStateNormal];
    timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(openCode) userInfo:nil repeats:YES];
}
-(void)openCode
{
    codeTimer--;
    if (codeTimer==0) {
        
        [codeButton setBackgroundColor:GET_COLOR(@"ff8cb7")];
        [codeButton setAlpha:1];
        [codeButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [codeButton setShowsTouchWhenHighlighted:YES];
        
        [codeButton setTitle:@"获取验证码" forState:UIControlStateNormal];
        [timer invalidate];
        timer = nil;
    }else{
        NSString *text = [NSString stringWithFormat:@"发送中(%d)",codeTimer];
        [codeButton setTitle:text forState:UIControlStateNormal];
    }
}

//获取验证码
-(void)getButt:(UIButton*)button
{
//    fieldView1.textField.text = @"18201122110";
    
    if ([button.titleLabel.text isEqualToString:@"获取验证码"]) {
        if (fieldView1.textField.text.length != 11) {
            [LoadingFrameView autoDisappearTipview:@"请输入11位数的手机号码"];
        }else{
            
            //判断当前设备发送短信次数
            NSMutableArray *array = [NSMutableArray arrayWithArray:[[APP_USERDEFAULTS valueForKey:APP_SEND_CODE_LOCK_PHONE] objectFromJSONString]];
            if (array.count>=APP_SEND_CODE_NUMBER) {
                CGFloat gap = [[NSDate date] timeIntervalSince1970]-[[array.firstObject objectForKey:APP_SEND_CODE_LOCK_TIME] floatValue];
                CLog(@"===%f===",gap);
                if (gap>60*30) {
                    [array removeObjectAtIndex:0];
                    [APP_USERDEFAULTS setValue:[array JSONString] forKey:APP_SEND_CODE_LOCK_PHONE];
                }else{
                    [LoadingFrameView autoDisappearTipview:@"当前操作频繁，请过30分钟后重试"];
                    return;
                }
            }
            
            [self closeKeyboard];
            if ([(NSObject*)self.delegate respondsToSelector:@selector(getPass)]) {
                [self.delegate getPass];
            }
        }
    }
}

//完成
-(void)doneButt
{
    if (fieldView1.textField.text.length != 11) {
        [LoadingFrameView autoDisappearTipview:@"请输入11位数的手机号码"];
    }else if (fieldView2.textField.text.length==0){
        [LoadingFrameView autoDisappearTipview:@"请输入验证码"];
    }else if (fieldView3.textField.text.length==0){
        [LoadingFrameView autoDisappearTipview:@"请输入密码"];
//    }else if (fieldView4.textField.text.length==0 && viewType==Update_Type){
    }else if (fieldView4.textField.text.length==0){
        [LoadingFrameView autoDisappearTipview:@"请输入确认密码"];
//    }else if (viewType==Update_Type && ![fieldView4.textField.text isEqualToString:fieldView3.textField.text]){
    }else if (![fieldView4.textField.text isEqualToString:fieldView3.textField.text]){
        [LoadingFrameView autoDisappearTipview:@"输入密码不一致"];
    }else{
        [self closeKeyboard];
        if ([(NSObject*)self.delegate respondsToSelector:@selector(done)]) {
            [self.delegate done];
        }
    }
}

//键盘右下角事件
-(void)nextButt:(UITextField*)textField
{
    if ([textField isEqual:fieldView2.textField]) {
        [fieldView3.textField becomeFirstResponder];
    }else if([textField isEqual:fieldView3.textField] ){
        if (fieldView4) {
            [fieldView4.textField becomeFirstResponder];
        }else{
            [self closeKeyboard];
        }
    }else{
        [self closeKeyboard];
    }
}

//关闭键盘
-(void)closeKeyboard
{
    [fieldView1.textField resignFirstResponder];
    [fieldView2.textField resignFirstResponder];
    [fieldView3.textField resignFirstResponder];
    [fieldView4.textField resignFirstResponder];
}

#pragma mark - UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    //最大字符个数
    NSInteger MAX_CHARS = 30;
    if ([textField isEqual:fieldView1.textField]) {
        MAX_CHARS = 11;
    }
    
    NSMutableString *newtxt = [NSMutableString stringWithString:textField.text];
    [newtxt replaceCharactersInRange:range withString:string];
    
    return ([newtxt length] <= MAX_CHARS);
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    if ([textField isEqual:fieldView4.textField]) {
        CGFloat height = CURRENT_CONTENT_HEIGHT-(fieldView4.frame.origin.y+fieldView4.frame.size.height-mainScroll.contentOffset.y+NAVIGATIONBAR_HEIGHT);
        if (height < 216) {
            CGFloat y = fieldView4.frame.origin.y+fieldView4.frame.size.height-(CURRENT_CONTENT_HEIGHT-216-NAVIGATIONBAR_HEIGHT);
            CGRect rect = mainScroll.frame;
            rect.size.height-=y;
            [mainScroll setFrame:rect];
            [mainScroll setContentOffset:CGPointMake(0, y)];
        }
    }
    return YES;
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
    if ([textField isEqual:fieldView4.textField]) {
        [mainScroll setFrame:self.bounds];
        [mainScroll setContentOffset:CGPointMake(0, 0)];
    }
    return YES;
}

@end
